package com.itheima.web.manager;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.HttpUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class WXLoginManager {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    @Value("${wx.accessTokenUrl}")
    private String accessTokenUrl;
    @Value("${wx.wxInfoUrl}")
    private String wxInfoUrl;

    @DubboReference
    private AdminService adminService;

    public ResponseEntity wxLogin(String code) {
        String atUtl=accessTokenUrl + "?code="+code+"&appid="+appid+"&secret="+secret+"&grant_type=authorization_code";
        Map<String, Object> map = HttpUtils.sendGet(atUtl);
        String openid = (String) map.get("openid");
        String accessToken = (String) map.get("access_token");
        Admin admin = adminService.findByOpenId(openid);
        if (admin!=null){
           return ResponseEntity.ok("登录成功");
        }else {
            System.out.println("绑定并登录");
            String wxurl = wxInfoUrl + "?access_token=" + accessToken +"&openid="+openid;
            Map<String, Object> map1 = HttpUtils.sendGet(wxurl);
            String nickname = (String) map1.get("nickname");
            String avatar = (String) map1.get("headimgurl");
            openid = (String) map1.get("openid");
            admin=new Admin();
            admin.setUsername(nickname);
            admin.setAvatar(avatar);
            admin.setOpenId(openid);
            admin.setPassword(SecureUtil.md5("123456"));
            adminService.saveAdmin(admin);
            return ResponseEntity.ok("绑定并登录成功");
        }



    }
}
